package com.xiebishe.mylibrary.net.retrofit.fastjsonConverter;

import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.xiebishe.mylibrary.base.MyApplication;
import com.xiebishe.mylibrary.net.retrofit.bean.NetBaseBean;


import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class FastJsonConverterFactory extends Converter.Factory {

    public static FastJsonConverterFactory create() {
        return new FastJsonConverterFactory();
    }

    private static final ParameterizedType voidType = new ParameterizedTypeImpl(new Type[]{null}, null, NetBaseBean.class);

    private FastJsonConverterFactory() {
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations, Retrofit retrofit) {
        return new FastJsonRequestBodyConverter<>();
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return getConverter(annotations, type);
    }


    /**
     * 根据annotation决定是否需要保留HTML标签
     *
     * @param annotations
     * @param type
     * @return
     */
    private static Converter<ResponseBody, ?> getConverter(Annotation[] annotations, Type type) {

        //如果是NetBaseBean<Void> 的type的话，因为fastjson 不支持Void范型， 把Void范型擦除
        if (type instanceof ParameterizedType) {
            Class<?> rawType = getRawType(type);
            if (rawType == NetBaseBean.class) {
                Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
                if (actualTypeArguments != null && actualTypeArguments.length > 0) {
                    if (actualTypeArguments[0] == Void.class)
                        type = voidType;
                }
            }

        }
        for (Annotation annotation : annotations) {
            if (annotation instanceof KeepHTML) {
                return new FastJsonResponseBodyConverter<>(type);
            }
            if (annotation instanceof DecryptBody){
                FastJsonResponseBodyDecodeConverter decodeConverter=MyApplication.getInstance().getDecryptFastJsonResponseBody(type);
                if (decodeConverter != null) {
                    return decodeConverter;
                }
            }
        }
        return new FastJsonResponseBodyDecodeConverter<>(type);
    }
}
